package com.cangxuan.backend.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cangxuan.backend.dao.IBillDao;
import com.cangxuan.backend.dao.IGoodsDao;
import com.cangxuan.backend.dao.IOrderFormDao;
import com.cangxuan.backend.dao.IUserGoodsDao;
import com.cangxuan.backend.entity.Goods;
import com.cangxuan.backend.entity.OrderForm;
import com.cangxuan.backend.entity.UserAmountRecord;
import com.cangxuan.backend.entity.UserGoods;
import com.cangxuan.backend.exception.ServiceException;
import com.cangxuan.backend.service.IOrderFormService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.List;


@Service
public class OrderFormServiceImpl extends BaseServiceImpl implements IOrderFormService {

    IGoodsDao goodsDao;
    IOrderFormDao orderFormDao;
    IUserGoodsDao userGoodsDao;
    IBillDao billDao;
    DataSourceTransactionManager transactionManager;

    @Autowired
    public void setBillDao(IBillDao billDao) {
        this.billDao = billDao;
    }

    @Autowired
    public void setUserGoodsDao(IUserGoodsDao userGoodsDao) {
        this.userGoodsDao = userGoodsDao;
    }

    @Autowired
    public void setGoodsDao(IGoodsDao goodsDao) {
        this.goodsDao = goodsDao;
    }

    @Autowired
    public void setOrderFormDao(IOrderFormDao orderFormDao) {
        this.orderFormDao = orderFormDao;
    }

    @Autowired
    public void setTransactionManager(DataSourceTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }


    @Override
    public synchronized JSONObject creatOrderForm(Integer goodsId, Integer count) {
        DefaultTransactionDefinition definition1 = new DefaultTransactionDefinition();
        definition1.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
        definition1.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus transaction1 = transactionManager.getTransaction(definition1);
        JSONObject jsonObject = new JSONObject();
        int res = 0;
        int userId = getCurrentUser().getId();

        int row = orderFormDao.selectUserHavaOrderForm(userId);
        if (row != 0) {
            transactionManager.rollback(transaction1);
            throw new ServiceException(415, "对不起你还有未支付的订单，请先完成订单");
        }

        Goods goods = goodsDao.selectGoodsByIdForUpdate(goodsId);
        if(goods.getCirculation().equals(goods.getMintage())){
            transactionManager.rollback(transaction1);
            throw new ServiceException(415, "创建订单失败，商品已售罄");
        }

        if (goods.getCirculation() + count > goods.getMintage()) {
            transactionManager.rollback(transaction1);
            throw new ServiceException(415, "创建订单失败，输入数量有误");
        }


        try {
            OrderForm orderForm = new OrderForm(0, userId, 100000, goodsId, Float.valueOf(goods.getPrice()), count, Float.valueOf(goods.getPrice() * count), 0, Float.valueOf(goods.getPrice() * count), null, null, 1, 0, null, null, null);
            //修改成功，创建订单，createOrderForm
            res+=orderFormDao.createOrderForm(orderForm);
            int orderFormId = orderForm.getId();
            if (res == 1) {
                //查询出orderform
                OrderForm returnOrderForm = orderFormDao.selectById(orderFormId);
                //通过Id查询Goods并返回Goods信息和sum
                jsonObject.put("orderform", returnOrderForm);
                jsonObject.put("sum", Float.valueOf(returnOrderForm.getTransAmount()));
                transactionManager.commit(transaction1);
                return jsonObject;
            } else {
                throw new ServiceException(415, "创建订单失败");
            }
        } catch (Exception e) {
            transactionManager.rollback(transaction1);
            throw new ServiceException(415, "创建订单失败");
        }

    }


    @Override
    public int successPay(int orderId) {
        DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
        definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        definition.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
        TransactionStatus transaction = transactionManager.getTransaction(definition);
        int res = 0;
        int max = 0;
        int userId = getCurrentUser().getId();


        //查询goodsId
        OrderForm orderForm = orderFormDao.selectByIdForUpdate(orderId);
        if (orderForm==null){
            transactionManager.rollback(transaction);
            throw new ServiceException(415, "支付失败");
        }
        //查询商品，流通量加上数量是否充足
        Goods goods = goodsDao.selectGoodsByIdForUpdate(orderForm.getGoodsId());

        //判断是否超时?
        int isOver = orderFormDao.selectIsOverTime(orderForm.getId());
        if (isOver>0){
            orderFormDao.updateForCancel(orderForm.getId());
            transactionManager.commit(transaction);
            throw new ServiceException(415, "订单超时");
        }


        //已卖完
        if (goods.getMintage()==goods.getCirculation()){
            orderFormDao.updateForCancel(orderForm.getId());
            transactionManager.commit(transaction);
            throw new ServiceException(415, "藏品已售罄");
        }

        try {

            //超卖
            if (goods.getMintage() <= goods.getCirculation() + orderForm.getCount()) {
                //修改订单数量为最大值
                max = goods.getMintage()-goods.getCirculation() ;
                res += orderFormDao.updateCount(orderForm.getId(), max, orderForm.getPrice() * max);
                res += goodsDao.updateCirculation(goods.getId(), max);
                orderForm = orderFormDao.selectByIdForUpdate(orderId);
            } else {
                res += goodsDao.updateCirculation(goods.getId(), orderForm.getCount());
            }

            //修改orderform,state和paytime
            res += orderFormDao.updateForSuccessPay(orderId);
            //创建user_goods
            res += userGoodsDao.insertForGoods(new UserGoods(userId, orderForm.getGoodsId(), null, orderForm.getCount()));
            //创建user_amount_record
            UserAmountRecord userAmountRecord = new UserAmountRecord(userId, 0, orderForm.getTransAmount(), "支出：" + orderForm.getTransAmount() + "元，购买主页的" + orderForm.getGoodsId() + "号藏品", orderId);
            res += billDao.insertRecord(userAmountRecord);


            if (res == 4 && max == 0) {
                transactionManager.commit(transaction);
                return orderForm.getCount();
            } else if (res == 5 && max != 0) {
                transactionManager.commit(transaction);
                return max;
            } else {
                throw new ServiceException(415, "支付失败");
            }
        } catch (Exception e) {
            transactionManager.rollback(transaction);
            throw new ServiceException(415, "支付失败");
        }

    }

    @Override
    public int cancelOderForm(int orderId) {
        DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
        definition.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
        definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus transaction = transactionManager.getTransaction(definition);
        int res = 0;

        try {
            //修改orderform状态
            res += orderFormDao.updateForCancel(orderId);
            if (res == 1) {
                transactionManager.commit(transaction);
                return res;
            } else {
                throw new ServiceException(415, "取消订单失败");
            }
        } catch (Exception e) {
            transactionManager.rollback(transaction);
            throw new ServiceException(415, "取消订单失败");
        }

    }

    @Override
    public List<OrderForm> getOderForm(int comeFrom, int state) {
        int userId = getCurrentUser().getId();
        List<OrderForm> list = orderFormDao.selectOrderForm(comeFrom, state, userId);

        return list;
    }

    @Override
    public void tryCancelOverTime(int orderId) {
        DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
        definition.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
        definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus transaction = transactionManager.getTransaction(definition);
        int res = 0;
        String message = "超时判断失败";
        try {
            if (orderFormDao.selectIsOverTime(orderId) != 0) {
                //修改orderform状态
                res += orderFormDao.updateForCancel(orderId);
                if (res == 1) {
                    message = "订单超时";
                    transactionManager.commit(transaction);
                    throw new ServiceException(415, "订单超时");
                } else {
                    message = "取消订单失败";
                    transactionManager.rollback(transaction);
                    throw new ServiceException(415, "取消订单失败");
                }
            } else {
                transactionManager.commit(transaction);
            }
        } catch (Exception e) {
            throw new ServiceException(415, message);
        }
    }
}
